<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class GoodsAttr extends Model
{
    protected $table = 'goods_attr';

    public $timestamps = false;

    /**
     * 获取某个商品的属性
     *
     * @param $goods_id
     * @return array
     */
    public static function getAttrByGoodsId($goods_id)
    {
        $res = [];
        $data = [];
        $parentNames = [];
        $list = self::where('goods_id', $goods_id)->get()->toArray();

        foreach ($list as $row) {
            if ($row['pid'] == 0) {
                $parentNames[$row['id']] = $row['name'];
            } else {
                $data[$row['pid']][] = $row;
            }
        }

        foreach ($parentNames as $pid => $name) {
            $res[$name] = $data[$pid];
        }
        return $res;
    }

    /**
     * 保存规格
     *
     * @param $goods_id
     * @param array $info
     */
    public static function saveAttr($goods_id, $info = [])
    {
        self::where('goods_id', $goods_id)->delete();
        if (!empty($info)) {
            foreach ($info as $parentName => $list) {
                $data = [];
                $pid = self::insertGetId(['goods_id' => $goods_id, 'pid' => 0, 'name' => $parentName]);
                foreach ($list as $row) {
                    $data[] = [
                        'goods_id' => $goods_id,
                        'pid' => $pid,
                        'name' => $row['name'],
                    ];
                }
                self::insert($data);
            }
        }
    }
}
